package com.example.treehole.ui.page.createPost

import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import com.example.treehole.service.DataRepository
import com.example.treehole.ui.component.showTreeholeSnackbar
import com.example.treehole.ui.model.PostType

class CreatePostViewModel : ViewModel() {
    val title = mutableStateOf("")
    val selectedTag = mutableStateOf(PostType.NO_TYPE)
    val content = mutableStateOf("")

    fun updateTitle(newTitle: String) {
        title.value = newTitle
    }

    fun updateSelectedTag(newTag: PostType) {
        selectedTag.value = newTag
    }

    fun updateContent(newContent: String) {
        content.value = newContent
    }

    fun clearData() {
        title.value = ""
        selectedTag.value = PostType.NO_TYPE
        content.value = ""
    }

    suspend fun uploadPost(
        jwlToken: String,
        userId: Int,
    ): Boolean {
        if (title.value.isEmpty() || content.value.isEmpty()) {
            showTreeholeSnackbar("标题内容不能为空")
            return false
        } else {
            val res =
                DataRepository.createPost(
                    jwlToken,
                    userId,
                    title.value,
                    content.value,
                    emptyList(),
                    selectedTag.value.ordinal
                )
            //            val res = 1
            res?.let {
                return true
            }
                ?: return false
        }
    }
}
